﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InfiniteRogue.AI
{
    public class SmartMonsterAI : AI
    {
        public SmartMonsterAI(Character c, Engine e)
            : base(c, e)
        {

        }

        public override void Turn()
        {
            if(character.LastEnemy != null && character.LastEnemy.Stats[StatSystem.HP] <= 0)
            {
                character.LastEnemy = null;
            }

            if(character.LastEnemy == null)
            {
                RandomMove();
            }
            else if(character.LastEnemy != null)
            {
                if(character.LastEnemy.Pos.InTarget(character.Pos, 1))
                {
                    engine.Rules.Combat.MeleeAttackSingle(character, character.LastEnemy);
                }
                else
                {
                    Tuple<int, int> move = MoveToward(character.LastEnemy.Pos);
                    engine.MoveNPC(character, move.Item1, move.Item2);
                }
            }
        }

        private void Explore()
        {

        }

        private void Wander()
        {
            int dx = Utilities.GlobalRandom.Next(3) - 1;
            int dy = Utilities.GlobalRandom.Next(3) - 1;
            engine.MoveNPC(character, dx, dy);
        }

        /// <summary>
        /// Different from Wander in that if the move isn't possible a new move is chosen until all 8 directions are tried.
        /// </summary>
        private void RandomMove()
        {
            List<Tuple<int, int>> possibleMoves = new List<Tuple<int, int>>(Utilities.Moves);
            while (possibleMoves.Count > 0)
            {
                int choice = Utilities.GlobalRandom.Next(possibleMoves.Count);
                Tuple<int, int> move = possibleMoves[choice];
                possibleMoves.RemoveAt(choice);
                if (engine.MoveNPC(character, move.Item1, move.Item2)) break;
            }
        }
    }
}
